<script setup>
import axios from 'axios';
import { ref } from 'vue';

const movies = ref([]);
const MovieData = ref('');
const showModal = ref(false);
const editingMovie = ref({});

const fetchData = async () => {
    const response = await axios.get('http://localhost:3000/movies');
    movies.value = response.data.data;
}
const btnAdd = () => {
  editingMovie.value = {};
};

const btnEdit = (movie) => {
  editingMovie.value = { ...movie };
  showModal.value = true;
};

const handleConfirm = () => {
  let id = editingMovie.value.id;
  let { name, director, rating } = editingMovie.value;
  let obj = { name, director, rating };

  let requestPromise = id > 0 ? axios.put(`http://localhost:3000/movies/${id}`, obj) : axios.post(`http://localhost:3000/movies`, obj);

  requestPromise.then(() => {
    showModal.value = false;
    fetchData();
  });
};

const handleCancel = () => {
  showModal.value = false;
};

const btnDel = (id) => {
  if (confirm(`确认删除吗？`)) {
    axios.delete(`http://localhost:3000/movies/${id}`).then(() => {
      fetchData();
    });
  }
};

const btnQuery = () => {
  axios.get(`http://localhost:3000/movies?keyword=${MovieData.value}`).then((res) => {
    movies.value = res.data.data;
  });
};

fetchData();
</script>

<template>
  <div>
    <input v-model="MovieData" placeholder="请输入查找关键词">
    <button @click="btnQuery">查找</button>
    <button @click="btnAdd(); showModal=true">添加</button>

    <table>
      <tr>
        <th>id</th>
        <th>电影名称</th>
        <th>导演</th>
        <th>分数</th>
        <th>操作</th>
      </tr>
      <tr v-for="movie in movies" :key="movie.id">
        <td>{{ movie.id }}</td>
        <td>{{ movie.name }}</td>
        <td>{{ movie.director }}</td>
        <td>{{ movie.rating }}</td>
        <td>
          <button @click="btnEdit(movie)">修改</button>
          <button @click="btnDel(movie.id)">删除</button>
        </td>
      </tr>
    </table>
  </div>

  <div v-if="showModal" class="modal">
    <div class="modal-content">
      <div>
        影名: <input v-model="editingMovie.name" placeholder="电影名称">
      </div>
      <div>
        导演: <input v-model="editingMovie.director" placeholder="导演名称">
      </div>
      <div>
        分数: <input v-model="editingMovie.rating" placeholder="分数"></div>
      <div>
        <button @click="handleConfirm">保存</button>
        <button @click="handleCancel">取消</button>
      </div>
    </div>
  </div>
</template>